package com.ruicar.afs.cloud.basic.proceeds.wechat.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.common.entity.BasicMainInfo;
import com.ruicar.afs.cloud.basic.common.entity.BasicPenaltyInterest;
import com.ruicar.afs.cloud.basic.common.entity.BasicRepaymentPlan;
import com.ruicar.afs.cloud.basic.common.service.BasicMainInfoService;
import com.ruicar.afs.cloud.basic.common.service.BasicPenaltyInterestService;
import com.ruicar.afs.cloud.basic.common.service.BasicRepaymentPlanService;
import com.ruicar.afs.cloud.basic.proceeds.debit.entity.BasicDebitBatchDetails;
import com.ruicar.afs.cloud.basic.proceeds.debit.service.BasicDebitBatchDetailsService;
import com.ruicar.afs.cloud.basic.proceeds.wechat.condition.CommonQueryCondition;
import com.ruicar.afs.cloud.basic.proceeds.wechat.vo.*;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.DebitStatusEnum;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-08-08 11:19
 */

@Slf4j
@RestController
@Api("微信对接controller")
@RequestMapping("/wechatOperation")
@AllArgsConstructor
public class WechatOperationController {

    private final BasicRepaymentPlanService basicRepaymentPlanService;
    private final BasicMainInfoService basicMainInfoService;
    private final BasicDebitBatchDetailsService basicDebitBatchDetailsService;
    private final BasicPenaltyInterestService basicPenaltyInterestService;


    /**
     * 还款计划查询
     * @author ZC.GUO
     * @param 
     * @return 
     */
    @PostMapping(value = "/queryRepaymentPlan")
    @ApiOperation(value = "还款计划查询")
    public IResponse<PlanMainInfo> queryRepaymentPlan(@RequestBody CommonQueryCondition commonQueryCondition) {
        PlanMainInfo planMainInfo = new PlanMainInfo();
        List<RepaymentPlan> repaymentPlanList = new ArrayList<>();
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,commonQueryCondition.getContractNo())
        );
        if (EmptyUtils.isNotEmpty(mainInfo)){
            planMainInfo.setApplyNo(mainInfo.getApplyNo());
            planMainInfo.setContractId(mainInfo.getId());
            planMainInfo.setContractNo(mainInfo.getContractNo());

            List<BasicRepaymentPlan> planList = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                    .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
            );
            if (EmptyUtils.isNotEmpty(planList)){
                planList.forEach(plan ->{
                    RepaymentPlan repaymentPlan = new RepaymentPlan();
                    repaymentPlan.setTermNo(plan.getTermNo());
                    repaymentPlan.setDueDate(DateUtil.format(plan.getDueDate(),"yyyy-MM-dd"));
                    repaymentPlan.setReceivableRent(plan.getReceivableRent().setScale(2, BigDecimal.ROUND_HALF_UP));
                    repaymentPlanList.add(repaymentPlan);
                });
            }
            planMainInfo.setRepaymentPlan(repaymentPlanList);
            return IResponse.success(planMainInfo);
        }else{
            return IResponse.fail("合同号不存在");
        }
    }


    /**
     * 查询扣款成功未回盘
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryDebitStatus")
    @ApiOperation(value = "查询扣款成功未回盘")
    public IResponse<DebitStatusInfo> queryDebitStatus(@RequestBody CommonQueryCondition commonQueryCondition) {
        DebitStatusInfo debitStatusInfo = new DebitStatusInfo();
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,commonQueryCondition.getContractNo())
        );
        if (EmptyUtils.isNotEmpty(mainInfo)){
            debitStatusInfo.setApplyNo(mainInfo.getApplyNo());
            debitStatusInfo.setContractId(mainInfo.getId());
            debitStatusInfo.setContractNo(mainInfo.getContractNo());

            List<BasicDebitBatchDetails> debitBatchDetailsList = basicDebitBatchDetailsService.list(Wrappers.<BasicDebitBatchDetails>query().lambda()
                    .eq(BasicDebitBatchDetails::getContractNo,mainInfo.getContractNo())
                    .eq(BasicDebitBatchDetails::getStatus, DebitStatusEnum.noResult)
            );
            if (EmptyUtils.isNotEmpty(debitBatchDetailsList)){
                debitStatusInfo.setDebitCount(debitBatchDetailsList.size());
                debitStatusInfo.setDebitAccount(debitBatchDetailsList.get(0).getDebitAccount());
            }else {
                debitStatusInfo.setDebitCount(BigDecimal.ZERO.intValue());
                debitStatusInfo.setDebitAccount("");
            }
            return IResponse.success(debitStatusInfo);
        }else{
            return IResponse.fail("合同号不存在");
        }
    }
    /**
     * 已还记录
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryRepaymentSettleAmt")
    @ApiOperation(value = "已还记录")
    public IResponse<List<RepaymentSettle>> queryRepaymentSettleAmt(@RequestBody CommonQueryCondition commonQueryCondition) {
        List<RepaymentSettle> repaymentSettleList = new ArrayList<>();
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,commonQueryCondition.getContractNo())
        );
        if (EmptyUtils.isNotEmpty(mainInfo)){
            List<BasicRepaymentPlan> planList = basicRepaymentPlanService.list(Wrappers.<BasicRepaymentPlan>query().lambda()
                    .eq(BasicRepaymentPlan::getContractNo,mainInfo.getContractNo())
            );
            if (EmptyUtils.isNotEmpty(planList)){
                planList.forEach(plan ->{
                    RepaymentSettle repaymentSettle = new RepaymentSettle();
                    repaymentSettle.setContractId(mainInfo.getId());
                    repaymentSettle.setTermNo(plan.getTermNo());
                    repaymentSettle.setDueDate(DateUtil.format(plan.getDueDate(),"yyyy-MM-dd"));
                    repaymentSettle.setReceivableRent((EmptyUtils.isNotEmpty(plan.getReceivableRent())?plan.getReceivableRent():BigDecimal.ZERO).setScale(2,BigDecimal.ROUND_HALF_UP));
                    repaymentSettle.setActualRent((EmptyUtils.isNotEmpty(plan.getActualRent())?plan.getActualRent():BigDecimal.ZERO).setScale(2,BigDecimal.ROUND_HALF_UP));
                    repaymentSettle.setAdjustedAmt(BigDecimal.ZERO.setScale(2,BigDecimal.ROUND_HALF_UP));

                    BasicPenaltyInterest penaltyInterest = basicPenaltyInterestService.getOne(Wrappers.<BasicPenaltyInterest>query().lambda()
                            .eq(BasicPenaltyInterest::getContractNo,mainInfo.getContractNo())
                            .eq(BasicPenaltyInterest::getTermNo,plan.getTermNo())
                    );
                    repaymentSettle.setPenaltyReceivedAmt((EmptyUtils.isNotEmpty(penaltyInterest)?penaltyInterest.getReceivedAmt():BigDecimal.ZERO).setScale(2,BigDecimal.ROUND_HALF_UP));
                    repaymentSettle.setSumSettleAmt(repaymentSettle.getActualRent().add(repaymentSettle.getPenaltyReceivedAmt()));
                    repaymentSettleList.add(repaymentSettle);
                });
            }
            return IResponse.success(repaymentSettleList);
        }else{
            return IResponse.fail("合同号不存在");
        }
    }

    /**
     * 查询应还，已还(每笔)
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryRepayment")
    @ApiOperation(value = "查询应还，已还(每笔)")
    public IResponse<RepaymentInfo> queryRepayment(@RequestBody CommonQueryCondition commonQueryCondition) {
        RepaymentInfo repaymentInfo = new RepaymentInfo();
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>query().lambda()
                .eq(BasicMainInfo::getContractNo,commonQueryCondition.getContractNo())
        );
        if (EmptyUtils.isNotEmpty(mainInfo)){
            repaymentInfo.setContractId(mainInfo.getId());

        }else{
            return IResponse.fail("合同号不存在");
        }
        return  IResponse.success(repaymentInfo);
    }

}
